<template>
  <div class="comment-section">
    <a-card title="评论区" :bordered="false">
      <!-- 发表评论 -->
      <div class="comment-form">
        <a-form layout="vertical" :model="commentForm">
          <a-form-item>
            <a-textarea
              v-model:value="commentForm.content"
              :rows="3"
              placeholder="写下你的评论..."
              :disabled="!isLoggedIn"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              :disabled="!isLoggedIn || !commentForm.content"
              @click="submitComment"
              :loading="submitting"
            >
              发表评论
            </a-button>
            <a-typography-text v-if="!isLoggedIn" type="secondary" style="margin-left: 10px">
              请先登录后再评论
            </a-typography-text>
          </a-form-item>
        </a-form>
      </div>

      <!-- 评论列表 -->
      <a-divider />
      <div class="comment-list">
        <a-spin :spinning="loading">
          <a-empty v-if="commentList.length === 0" description="暂无评论" />
          <a-list
            v-else
            item-layout="horizontal"
            :data-source="commentList"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-comment
                  :author="item.user?.userName || '匿名用户'"
                  :avatar="item.user?.userAvatar"
                  :content="item.content"
                  :datetime="formatDate(item.createTime)"
                >
                  <template #actions>
                    <span v-if="canDelete(item)" key="delete" @click="deleteComment(item.id)">
                      <delete-outlined /> 删除
                    </span>
                  </template>
                </a-comment>
              </a-list-item>
            </template>
          </a-list>
          
          <!-- 分页 -->
          <div class="pagination" v-if="commentList.length > 0">
            <a-pagination
              v-model:current="current"
              :total="total"
              :pageSize="pageSize"
              @change="handlePageChange"
              size="small"
              show-quick-jumper
              show-size-changer
              :pageSizeOptions="['5', '10', '20']"
              @showSizeChange="handleSizeChange"
            />
          </div>
        </a-spin>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { DeleteOutlined } from '@ant-design/icons-vue';
import { useLoginUserStore } from '@/stores/useLoginUserStore';
import { 
  addCommentUsingPost, 
  listCommentByPageUsingPost, 
  deleteCommentUsingPost 
} from '@/api/commentController';
import dayjs from 'dayjs';

const props = defineProps<{
  pictureId: number | string;
}>();

// 登录用户信息
const loginUserStore = useLoginUserStore();
const isLoggedIn = computed(() => !!loginUserStore.loginUser?.id);

// 评论表单
const commentForm = ref({
  pictureId: props.pictureId,
  content: '',
  parentId: 0
});

// 评论列表状态
const commentList = ref<API.CommentVO[]>([]);
const loading = ref(false);
const submitting = ref(false);
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 监听pictureId变化，重新加载评论
watch(() => props.pictureId, (newVal) => {
  if (newVal) {
    commentForm.value.pictureId = newVal;
    loadComments();
  }
});

// 加载评论列表
const loadComments = async () => {
  if (!props.pictureId) return;
  
  loading.value = true;
  try {
    const res = await listCommentByPageUsingPost({
      pictureId: props.pictureId,
      current: current.value,
      pageSize: pageSize.value,
      reviewStatus: 1, // 只显示审核通过的评论
      parentId: 0 // 只显示一级评论
    });
    
    if (res.data.code === 0 && res.data.data) {
      commentList.value = res.data.data;
      // 假设后端返回了总数，如果没有，可以根据实际情况调整
      total.value = res.data.total || commentList.value.length;
    } else {
      message.error('获取评论失败：' + res.data.message);
    }
  } catch (error: any) {
    message.error('获取评论失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

// 提交评论
const submitComment = async () => {
  if (!commentForm.value.content.trim()) {
    message.warning('评论内容不能为空');
    return;
  }
  
  submitting.value = true;
  try {
    const res = await addCommentUsingPost({
      pictureId: props.pictureId,
      content: commentForm.value.content,
      parentId: commentForm.value.parentId
    });
    
    if (res.data.code === 0) {
      message.success('评论发布成功，等待审核');
      commentForm.value.content = ''; // 清空输入框
      
      // 如果是管理员发布的评论，会自动审核通过，所以需要重新加载评论列表
      if (loginUserStore.loginUser?.userRole === 'admin') {
        loadComments();
      }
    } else {
      message.error('评论发布失败：' + res.data.message);
    }
  } catch (error: any) {
    message.error('评论发布失败：' + error.message);
  } finally {
    submitting.value = false;
  }
};

// 删除评论
const deleteComment = async (id: number) => {
  try {
    const res = await deleteCommentUsingPost({ id });
    if (res.data.code === 0) {
      message.success('评论删除成功');
      loadComments(); // 重新加载评论列表
    } else {
      message.error('删除失败：' + res.data.message);
    }
  } catch (error: any) {
    message.error('删除失败：' + error.message);
  }
};

// 判断是否可以删除评论
const canDelete = (comment: API.CommentVO) => {
  const loginUser = loginUserStore.loginUser;
  if (!loginUser?.id) return false;
  
  // 管理员或评论作者可以删除
  return loginUser.userRole === 'admin' || loginUser.id === comment.userId;
};

// 分页变化
const handlePageChange = (page: number) => {
  current.value = page;
  loadComments();
};

// 每页条数变化
const handleSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  loadComments();
};

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 组件挂载时加载评论
onMounted(() => {
  if (props.pictureId) {
    loadComments();
  }
});
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>